package com.laomuji.android.mvvm.utils.language

import com.laomuji.android.mvvm.utils.cache.CacheUtil

/**
 * 国际化的语言国家码
 * @author laomuji666
 * @since 2024/2/20
 */
enum class LanguageCode {
    AUTO{
        override fun getAndroidLanguageCode(): String {
            val systemLanguageCode = LanguageUtil.getSysPreferredLocale().language
            for (entry in entries) {
                if(entry == AUTO || entry == LAST){
                    continue
                }
                if(entry.getAndroidLanguageCode() == systemLanguageCode){
                    return entry.getAndroidLanguageCode()
                }
            }
            return ENGLISH.getAndroidLanguageCode()
        }

        override fun getExportLanguageCode(): String {
            val systemLanguageCode = LanguageUtil.getSysPreferredLocale().language
            for (entry in entries) {
                if(entry == AUTO || entry == LAST){
                    continue
                }
                if(entry.getAndroidLanguageCode() == systemLanguageCode){
                    return entry.getExportLanguageCode()
                }
            }
            return ENGLISH.getExportLanguageCode()
        }
    }, LAST{
        override fun getAndroidLanguageCode(): String = getLastLanguageCode()

        override fun getExportLanguageCode(): String {
            val androidLanguageCode = getLastLanguageCode()
            for (entry in entries) {
                if(entry == AUTO || entry == LAST){
                    continue
                }
                if(entry.getAndroidLanguageCode() == androidLanguageCode){
                    return entry.getExportLanguageCode()
                }
            }
            return AUTO.getExportLanguageCode()
        }
    }, CHINESE{
        override fun getAndroidLanguageCode(): String = "zh"
        override fun getExportLanguageCode(): String = "zh"

    }, ENGLISH{
        override fun getAndroidLanguageCode(): String = "en"
        override fun getExportLanguageCode(): String = "en"
    }, INDONESIAN{
        override fun getAndroidLanguageCode(): String = "in"
        override fun getExportLanguageCode(): String = "id"
    }
    ;

    /**
     * 返回安卓系统需要的非标准国家码(安卓系统历史遗留问题)
     */
    abstract fun getAndroidLanguageCode():String
    /**
     * 返回外部需要的标准国家码
     */
    abstract fun getExportLanguageCode():String


    companion object{
        private const val LAST_LANGUAGE_CODE_ANDROID = "last_language_code_android"
        private var lastLanguageCodeAndroid: String by CacheUtil.cacheable(LAST_LANGUAGE_CODE_ANDROID, AUTO.getAndroidLanguageCode())

        fun getLastLanguageCode():String = lastLanguageCodeAndroid

        fun setLastLanguageCode(languageCode: LanguageCode){
            lastLanguageCodeAndroid = languageCode.getAndroidLanguageCode()
        }
    }
}